package com.taotao.shopping.service.impl;

import com.taotao.common.redis.service.RedisService;
import com.taotao.common.security.utils.SecurityUtils;
import com.taotao.shopping.constants.ShoppingConstants;
import com.taotao.shopping.domain.PmsCartItems;
import com.taotao.shopping.domain.response.CartResponse;
import com.taotao.shopping.mapper.ShoppingMapper;
import com.taotao.shopping.service.ShoppingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @className: ShoppingServiceImpl
 * @author: ZhangYuQi
 * @date: 2024/12/27 下午3:58
 * @Version: 1.0
 * @description:
 */

@Service
public class ShoppingServiceImpl implements ShoppingService {

    @Autowired
    private ShoppingMapper shoppingMapper;

    @Autowired
    private RedisService redisService;


    @Override
    public void addToCart(Long skuId, Integer quantity) {


        //获取当前登录用户
        Long userId = SecurityUtils.getUserId();
        //Long userId = 1L;
        String shoppingKey = ShoppingConstants.CART_KEY + userId;

        //判断用户是否有购物车
        if(!redisService.hasKey(shoppingKey)){
            //去数据库查询用户是否拥有购物车
            //如果用户未拥有购物车 则为用户创建一个购物车
            shoppingMapper.insertPmsCart(userId);
            //创建redis购物车
            redisService.setCacheMapValue(shoppingKey,skuId.toString(),null);
        }
        //如果用户拥有购物车 则取出对应商品的数据量
        if(redisService.getCacheMapValue(shoppingKey,skuId.toString())!=null){
            //如果用户拥有购物车 则取出对应商品的数据量
            Integer oldQuantity = Integer.parseInt(redisService.getCacheMapValue(shoppingKey, skuId.toString()).toString());
            //更新数量
            redisService.setCacheMapValue(shoppingKey,skuId.toString(),oldQuantity+quantity);
        }else{
            //如果用户购物车没有该商品 则添加商品
            redisService.setCacheMapValue(shoppingKey,skuId.toString(),quantity);
        }

    }

    @Override
    public Long selectCartByUserId(Long userId) {
        return shoppingMapper.selectCartByUserId(userId);
    }

    @Override
    public PmsCartItems selectCartItemsBySkuIdCartIdAndQuantity(Long skuId, Long cartId) {
        return shoppingMapper.selectCartItemsBySkuIdCartIdAndQuantity(skuId, cartId);
    }

    @Override
    public void addInBulkCartItems(ArrayList<PmsCartItems> addCartItemsList) {
        shoppingMapper.insertInBulkCartItems(addCartItemsList);
    }

    @Override
    public void updateInBulkCartItems(ArrayList<PmsCartItems> updateCartItemsList) {
        shoppingMapper.updateInBulkCartItems(updateCartItemsList);
    }

    @Override
    public List<CartResponse> shoppingCartList() {
        //获取当前登录用户id
        Long userId = SecurityUtils.getUserId();
        return shoppingMapper.selectUserCartList(userId);
    }


}
